# coding=utf-8
'''
Created on 2019年3月11日

@author: zy
'''
import os
import time
import subprocess
from multiprocessing import Process
from traverse.app_crawler import AppCrawler

def localCmd(*args):
    '''exec system cmd, paramas list'''
    cmd_line = list(args)
    if os.name != "nt":
        cmd_line = [" ".join(cmd_line)]
    return subprocess.Popen(cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)


def get_devices():
    out = localCmd("adb","devices").communicate()[0].decode('utf-8')
    match = "List of devices attached"
    index = out.find(match)
    if index < 0:
        raise EnvironmentError("adb is not working.")
    return dict([s.split("\t") for s in out[index + len(match):].strip().splitlines() if s.strip()])

def test(serial):
    AppCrawler({'serial':serial}).run()

def main():
    device_list = get_devices()
    if not device_list:
        raise RuntimeError('("not device found.")')
    pList = []
    for serial,status in device_list.items():
        if status == "device":
            p = Process(target=test,args=(serial,))
            p.start()
            pList.append(p)
    p_size = len(pList)
    while True:
        for p in pList:
            if not p.is_alive():
                p_size -= 1 
            if p_size == 0:
                break
            else:
                time.sleep(10) 
                
        
if __name__ == '__main__':
    main()
    